from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill
from datetime import datetime

# 初始化工作簿
wb = Workbook()
ws = wb.active
ws.title = "测试报告概览"
ws_summary = wb.create_sheet("详细数据")

# 1. 测试概览表头
headers = ["项目", "值"]
overview_data = [
    ["测试模块", "海拔显示模块V2.3"],
    ["测试版本", "HMI_202406_Build17"],
    ["测试时间", datetime.now().strftime("%Y-%m-%d %H:%M")],
    ["测试用例总数", 15],
    ["通过率", "93.3%"],
    ["致命缺陷", 0],
    ["阻塞缺陷", 2]
]

ws.append(["模块测试报告概览"])
for row in overview_data:
    ws.append(row)

# 2. 详细测试数据
detail_headers = ["用例ID", "测试项", "执行结果", "缺陷ID", "执行人", "耗时(s)"]
test_cases = [
    ["TC-001", "零值显示", "PASS", "-", "张三", 3.2],
    ["TC-002", "正海拔显示", "PASS", "-", "李四", 2.8],
    ["TC-003", "负值超限", "FAIL", "DEF-114", "王五", 4.5],
    ["TC-004", "信号丢失", "PASS", "-", "张三", 3.1],
    ["TC-005", "无效值处理", "BLOCKED", "DEF-115", "李四", 0]
]

ws_summary.append(detail_headers)
for case in test_cases:
    ws_summary.append(case)

# 3. 添加统计图表
chart = BarChart()
chart.title = "测试结果分布"
chart.y_axis.title = '数量'
chart.x_axis.title = '结果类型'
data = Reference(ws_summary, min_col=3, min_row=2, max_row=6, max_col=3)
cats = Reference(ws_summary, min_col=2, min_row=2, max_row=6)
chart.add_data(data, titles_from_data=False)
chart.set_categories(cats)
ws.add_chart(chart, "A10")

# 4. 样式美化
red_fill = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
for row in ws_summary.iter_rows(min_row=2, max_row=6, min_col=3, max_col=3):
    for cell in row:
        if cell.value == "FAIL":
            cell.fill = red_fill

# 保存文件
wb.save("模块测试报告.xlsx")
print("测试报告已生成：模块测试报告.xlsx")